package com.lemon.ui.codemaker;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import com.lemon.components.ant.beans.ProjectInfo;
import com.lemon.components.docs.mysql.MysqlLocalTool;
import com.lemon.ui.codemaker.dto.MenuNode;
import com.lemon.ui.codemaker.dto.SysMenu;

public class MenuSelect extends JDialog {


	private static final long serialVersionUID = -7312501456498072477L;
	private String host;
	private String dbname;
	private String userName;
	private String passwd;
	private JTree tree;
	private Long menuId;
	private DefaultTreeModel root;


	/**
	 * Create the dialog.
	 */
	public MenuSelect(String host, String dbname, String userName, String passwd) {
		
		this.host = host;
		this.dbname = dbname;
		this.userName = userName;
		this.passwd = passwd;
		
		setType(Type.UTILITY);
		setTitle("菜单选择");
		setBounds(100, 100, 360, 448);
		getContentPane().setLayout(new BorderLayout());
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton okButton = new JButton("确定");
				okButton.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent arg0) {
						MenuNode menuNode = (MenuNode) tree.getLastSelectedPathComponent();
						setMenuId(menuNode.getMenuId());
						dispose();
					}
				});
				okButton.setActionCommand("OK");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton cancelButton = new JButton("取消");
				cancelButton.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent e) {
						dispose();
					}
				});
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
			}
		}
		{
			JScrollPane scrollPane = new JScrollPane();
			getContentPane().add(scrollPane, BorderLayout.CENTER);
			{
				root = new DefaultTreeModel(createTree());
				tree = new JTree(root);
				tree.addMouseListener(new MouseAdapter() {

					@Override
					public void mouseClicked(MouseEvent e) {
						if (e.getSource() == tree && e.getClickCount() == 2) {
							TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
							if (selPath != null) {
		                        MenuNode node = (MenuNode) selPath.getLastPathComponent();
		                        if(!node.children().hasMoreElements()) {
		                        	setMenuId(node.getMenuId());
		                        	dispose();
		                        }
		                    }
						}
					}
					
				});
				tree.setToolTipText("选择菜单");
				JPopupMenu popupMenu = new JPopupMenu();
				JMenuItem mntmNewMenuItem = new JMenuItem("删除节点");
				mntmNewMenuItem.setIcon(new ImageIcon(this.getClass().getResource("/code/icon/delete.png")));
				popupMenu.add(mntmNewMenuItem);
				tree.addMouseListener(new MouseAdapter() {

					@Override
					public void mouseClicked(MouseEvent e) {
						super.mouseClicked(e);
						if(e.getButton()==MouseEvent.BUTTON3){
							TreePath pathForLocation = tree.getPathForLocation(e.getX(), e.getY());//获取右键点击所在树节点路径
							tree.setSelectionPath(pathForLocation);
							if(tree.getSelectionCount() > 0) {
								popupMenu.show(tree, e.getX(), e.getY());
							}
						}
					}
					
				});
				mntmNewMenuItem.addActionListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent e) {
						MenuNode menuNode = (MenuNode)tree.getLastSelectedPathComponent();
						try {
							root.removeNodeFromParent(menuNode);
							delNode(menuNode.getMenuId());
						} catch (Exception e2) {
							
						}
					}
				});
				scrollPane.setViewportView(tree);
			}
		}
	}
	
	public ProjectInfo getDbInfo() {
		ProjectInfo projectInfo = new ProjectInfo();
		projectInfo.setDbhost(getHost());
		projectInfo.setDbname(getDbname());
		projectInfo.setDbusername(getUserName());
		projectInfo.setDbpasswd(getPasswd());
		return projectInfo;
	}
	
	private DefaultMutableTreeNode createTree() {
		
		try(Connection connection = MysqlLocalTool.getConWithException(getDbInfo())) {
			
			PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM sys_menu");
			ResultSet resultSet = preparedStatement.executeQuery();
			List<SysMenu> list = new ArrayList<SysMenu>();
			while (resultSet.next()) {
				SysMenu sysMenu = new SysMenu();
				sysMenu.setMenuId(resultSet.getLong("menu_id"));
				sysMenu.setParentId(resultSet.getLong("parent_id"));
				sysMenu.setMenuName(resultSet.getString("menu_name"));
				list.add(sysMenu);
			}
			
			//获取root节点
			PreparedStatement rootNodePS = connection.prepareStatement("SELECT * FROM sys_menu WHERE parent_id = 0");
			ResultSet rootNodeRS = rootNodePS.executeQuery();
			MenuNode menuNode = new MenuNode("请选择");
			while (rootNodeRS.next()) {
				MenuNode rooter = new MenuNode(rootNodeRS.getString("menu_name"));
				rooter.setMenuId(rootNodeRS.getLong("menu_id"));
				MenuNode rootNode = nodebuild(rooter,list,null);
				menuNode.add(rootNode);
			}
			
			
			return menuNode;
		} catch (Exception e) {
			e.printStackTrace();
			
			return new DefaultMutableTreeNode("节点获取错误");
		}
	}
	
	private void delNode(Long nodeId) {
		try(Connection connection = MysqlLocalTool.getConWithException(getDbInfo())) {
			connection.setAutoCommit(false);
			PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM sys_menu");
			ResultSet resultSet = preparedStatement.executeQuery();
			List<SysMenu> list = new ArrayList<SysMenu>();
			while (resultSet.next()) {
				SysMenu sysMenu = new SysMenu();
				sysMenu.setMenuId(resultSet.getLong("menu_id"));
				sysMenu.setParentId(resultSet.getLong("parent_id"));
				sysMenu.setMenuName(resultSet.getString("menu_name"));
				list.add(sysMenu);
			}
			MenuNode rooter = new MenuNode("del");
			rooter.setMenuId(nodeId);
			ArrayList<Long> delNode = new ArrayList<Long>();
			nodebuild(rooter,list,delNode);
			preparedStatement = connection.prepareStatement("delete from sys_menu where menu_id=?");
			preparedStatement.setLong(1, nodeId);
			preparedStatement.addBatch();
			for(Long menuId:delNode) {
				preparedStatement.setLong(1, menuId);
				preparedStatement.addBatch();
			}
			preparedStatement.executeBatch();
			connection.commit();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	private MenuNode nodebuild(MenuNode pnode,List<SysMenu> list,List<Long> ids){
		for(SysMenu nodedo:list){
			if(nodedo.getParentId()!=0 && nodedo.getParentId().equals(pnode.getMenuId())){
				MenuNode node = new MenuNode(nodedo.getMenuName());
				node.setHref(nodedo.getMenuUrl());
				node.setMenuIcon(nodedo.getMenuIcon());
				node.setMenuId(nodedo.getMenuId());
				node.setSpread(false);
				node.setTitle(nodedo.getMenuName());
				node.setSort(nodedo.getSort()==null?99999:nodedo.getSort());
				if(ids != null)
					ids.add(nodedo.getMenuId());
				pnode.add(node);
				pnode.getChildren().add(node);
				nodebuild(node,list,ids);
			}
		}
		return pnode;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPasswd() {
		return passwd;
	}

	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}

	public String getDbname() {
		return dbname;
	}

	public void setDbname(String dbname) {
		this.dbname = dbname;
	}


	public Long getMenuId() {
		return menuId;
	}


	public void setMenuId(Long menuId) {
		this.menuId = menuId;
	}
	private static void addPopup(Component component, final JPopupMenu popup) {
		component.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}
			@Override
			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}
			private void showMenu(MouseEvent e) {
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		});
	}
}
